import { asyncRoutes, constantRoutes } from '@/router'
import { getRoutes } from '@/api/permission'
import router, { resetRouter } from '@/router'
import { getToken } from '@/utils/auth' // get token from cookie

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

function matchRoutes(list, matchList) {
  const matchArr = []
  for (const i of matchList) {
    matchArr.push(i.resourcePath)
  }
  // console.log(list, matchList)

  // 使用拷贝，不要在原引用上操作，concat方法是浅拷贝，内部成员引用还是同一个地址
  // JSON.parse(JSON.stringify(list))不能处理成员变量中的function-component
  // 使用死办法，for循环
  const addRoutes = []
  for (let i = 0; i < list.length; i++) {
    let element
    if (!list[i].hidden) {
      element = {
        path: '',
        component: null,
        alwaysShow: true,
        meta: null,
        children: []
      };
      element.path = list[i].path
      element.component = list[i].component
      element.meta = list[i].meta
      for (let j = 0; j < list[i].children.length; j++) {
        const element1 = list[i].children[j];
        element.children.push(element1)
      }
    } else {
      // 全屏路由另外处理
      if (list[i].path !== '*') {
        element = {
          path: '', 
          url: '', 
          component: null, 
          hidden: true
        }
        element.path = list[i].path
        element.url = list[i].url
        element.component = list[i].component
      } else {
        element = { path: '*', redirect: '/404', hidden: true }
      }
    }
    addRoutes.push(element)
  }
  // console.log('listCopy', addRoutes)
  let newList = addRoutes.map(e => {
    if(e.children) {
      e.children = e.children.filter(a => matchArr.indexOf(a.url) !== -1)
    } else {
      if (matchArr.indexOf(e.url) !== -1) return e
    }
    return e
  })
  newList = newList.filter((a, i) => !a.children || a.children.length > 0)
  // console.log('newList', newList)
  return newList
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    const hasToken = getToken()
    // console.log('hasToken', hasToken)
    return new Promise((resolve, reject) => {
      // 唯一界面权限
      if (hasToken === 'login-for-keyparts') {
        const accessedRoutes = matchRoutes(asyncRoutes, [{resourcePath: '/mes-web/keyparts-scan/index'}])
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      } else if (hasToken === 'login-for-reviewparts') {
        const accessedRoutes = matchRoutes(asyncRoutes, [{resourcePath: '/mes-web/reviewparts-scan/index'}])
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      } else {
        getRoutes().then(response => {
          const { data } = response
          if (!data || data.length <= 0) {
            reject('权限为空！')
          }
          let accessedRoutes
          accessedRoutes = matchRoutes(asyncRoutes, data)
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }).catch(error => {
          reject(error)
        })
      }
      
    })
    
    // return new Promise(resolve => {
    //   let accessedRoutes
    //   if (roles.includes('admin')) {
    //     accessedRoutes = asyncRoutes || []
    //   } else {
    //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
    //   }
    //   commit('SET_ROUTES', accessedRoutes)
    //   resolve(accessedRoutes)
    // })
  },
  resetRoutes({ commit }) {
    return new Promise(resolve => {
      commit('SET_ROUTES', [])
      resetRouter()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
